package com.ktjy.controller;

import com.ktjy.entity.SysUser;
import com.ktjy.service.SysUserService;
import com.ktjy.utils.Constants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

@Controller
public class LoginController extends BaseController{
    @Autowired
    SysUserService sysUserService;

    @GetMapping("/login")
    public String toLogin(){
        return forward("/login.jsp");
    }

    @PostMapping("/login")
    public String login(@RequestParam("account") String account,
                        @RequestParam("password") String password,
                        HttpServletRequest request,
                        HttpSession session){
        //调用service方法进行登录
        SysUser loginUser = sysUserService.login(account, password);
        if(loginUser!=null){//登录成功
            //1.将登录用户信息保存到session
            session.setAttribute(Constants.SESSION_USER,loginUser);
            //2.重定向到首页
            //字符串前面有一个redirect:表示重定向
            return redirect("/main/index");
        }else{//登录失败
//            //1.给出友好提示
//            request.setAttribute(Constants.REQUEST_ERROR,"用户名或者密码错误");
//            //2.转发到登录页面
//            //字符串前面有一个forward:表示转发
//            return forward("/login.jsp");

            throw new RuntimeException("用户名或者密码错误");
        }
    }

    @GetMapping("/main/index")
    public String index(){
        //普通字符串：默认转发到一个页面
        return "index";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return redirect("/login.jsp");
    }

//    @ExceptionHandler(value = RuntimeException.class)
//    public String handlerException(RuntimeException e,HttpServletRequest request){
//        request.setAttribute(Constants.REQUEST_ERROR,e);
//        return "500";
//    }
}
